package org.longs.converter.parser;

import org.longs.bean.PalRGB;

import java.awt.*;

public class IgnorePixelsParser implements Parser {
    @Override
    public boolean judge(int flag) {
        return flag >> 6 == 3;
    }

    @Override
    public void analysis(Recorder recorder, BufferedColorListener listener) {
        recorder.setFlag("IgnorePixels");
        int repeat = recorder.getByte() & 0x3F;
        if (repeat != 0) {
            for (int i = 0; i < repeat; i++) {
                int width = recorder.getBufferedImage().getWidth();
                if (width > recorder.getWidth()) {
                    recorder.setWidth(recorder.getWidth() + 1);
                }
            }
            return;
        }
        if (recorder.getWidth() - 1 < 0 || (recorder.getWidth() - 1 >= recorder.getBufferedImage().getWidth()) || (recorder.getBytes()[recorder.getOffset()] & 0x20) != 0x20) {
            recorder.getOffsetUp();
            return;
        }
        int alpha = recorder.getBytes()[recorder.getOffsetUp()] & 0x1F;
        alpha = (alpha << 3) | (alpha >> 2);
        PalRGB color = recorder.getPalRGBs()[recorder.getBytes()[recorder.getOffset()] & 0xFF];
        recorder.setWidth(recorder.getWidth() - 1);
        int upAlpha = (recorder.getBufferedImage().getRGB(recorder.getWidth(), recorder.getHeight()) >> 24)& 0xFF;
        if (alpha >upAlpha) {
            listener.result(new Color(color.getR(), color.getG(), color.getB(), alpha), recorder);
        }else{
            listener.result(new Color(recorder.getBufferedImage().getRGB(recorder.getWidth(), recorder.getHeight())), recorder);
        }
        recorder.getOffsetUp();
    }
}
